//
//  OAuthViewController.swift
//  SHWeibo2.0
//
//  Created by 黄礼潮 on 16/2/24.
//  Copyright © 2016年 黄礼潮. All rights reserved.
//

import UIKit



class OAuthViewController: UIViewController {
    
    private lazy var webView = UIWebView()
    
       override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        //加载页面发送网络请求
        self.webView.loadRequest(NSURLRequest(URL: NetworkTools.shardTools.oAuthNSURL))

    }

    override func loadView() {
        view = webView
        
        //设置代理
        webView.delegate = self
        
        title = "登录新浪微博"
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", style:.Plain, target:self, action:"clickAddFill")
        navigationItem.leftBarButtonItem = UIBarButtonItem(title:"取消", style:.Plain, target:self, action:"clickColseController")
        
        
    }
    
    @objc  private func clickColseController(){
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
}

extension OAuthViewController{
    
    @objc private  func clickAddFill(){
        
        let js = "document.getElementById('userId').value = '15805514085';" +
        "document.getElementById('passwd').value = 'clh19910103';"
        
        self.webView.stringByEvaluatingJavaScriptFromString(js)
        
    }
    
}

extension OAuthViewController:UIWebViewDelegate{

    //这个方法中  返回true 一切OK 如果返回false 那么就不正常执行
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        if let urlString = request.URL?.absoluteString where  !urlString.hasPrefix(NetworkTools.shardTools.redirectUri) {
            
            return true
            
        }
        
        
        guard let query = request.URL?.query where query.hasPrefix("code=") else{
            
            print("取消授权")
            
            dismissViewControllerAnimated(true, completion: nil)
            
            return false
            
        }
        
        let code = query.substringFromIndex("code=".endIndex)
        
        print("请求授权码"+code)
        
        NetworkTools.shardTools.loadAssess_token(code) { (result) -> () in
            
            guard let result = result else{
                
                print("数据加载错误")
                return
            }
            
            
            
            
            //保存用户信息  下面这段代码导致崩溃
            //NSUserDefaults.standardUserDefaults().setValuesForKeysWithDictionary(result)
            //UserAccount.shardUserAccount.saveUserAccount()
            //字典转模型
            //UserAccount.shardUserAccount.setValuesForKeysWithDictionary(result)
            //UserAccount.shardUserAccount.saveUserAccount()
            UserAccount.shardUserAccount.updateUserAccount(result)
            
            //发送通知
            NSNotificationCenter.defaultCenter().postNotificationName(CZWeiboNotification, object: nil)
           
            //关闭控制器
            
           dispatch_after(dispatch_time(DISPATCH_TIME_NOW,Int64(Double(NSEC_PER_SEC) * 1.0)), dispatch_get_main_queue(), { () -> Void in
            self.clickColseController()
            
           })
        }
        
        return true
    }


}
